package com.springboot.leaseHouse.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.leaseHouse.bean.Dto;
import com.springboot.leaseHouse.bean.Loginer;
import com.springboot.leaseHouse.service.TokenService;
import com.springboot.leaseHouse.service.impl.LoginerServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginerController
 * @Description //TODO
 * @Author 秦野
 * @Date 2021/9/2314:36
 */
@RestController
public class LoginerController {

    @Resource
    private LoginerServiceImpl loginerService;
    @Resource
    private TokenService tokenService;
    private Dto dto=new Dto();

    /**
     * 用户登录功能
     * @param name：用户名
     * @param password ：密码
     * @return 返回结果
     */
    @RequestMapping("/login")
    public Dto loginer(@Param("loginerName")String name,
                          @Param("loginerPassword")String password,
                          HttpServletRequest request){
        //条件构造器
        QueryWrapper<Loginer>  queryWrapper = new QueryWrapper<>();
        Map<String,String> map=new HashMap<>();
        map.put("loginerName",name);
        map.put("loginerPassword",password);
        //查询数据库
        queryWrapper.allEq(map);
        Loginer loginer = loginerService.getOne(queryWrapper);
        //登录成功
        if (loginer!=null){
            //获取用户代理（请求头中）
            String userAgentStr = request.getHeader("user-agent");
            //获取token
            String token = tokenService.gererateToken(userAgentStr, name);
            //保存到Redis中
            tokenService.save(token,loginer);
            //组织前台需要的信息
            dto.setIsLogin("success");
            dto.setToken(token);
            dto.setTokenCreatedDate(System.currentTimeMillis());
            dto.setTokenExpiryDate(System.currentTimeMillis()+7200000);
        }else{
            dto.setIsLogin("false");
        }
        return dto;
    }

}
